package com.sign2024.sign2024project.aop.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.sign2024.sign2024core.common.utils.SpringUtils;
import com.sign2024.sign2024core.common.utils.StringUtils;
import com.sign2024.sign2024core.entry.projectservice.BatchNeed;
import com.sign2024.sign2024project.projectservice.service.BatchNeedService;
import lombok.Data;

import java.util.List;

@Data
public class BatchNeedExcelListener implements ReadListener<BatchNeed> {

    /**
     * 控制层 所传参数
     */
    private Integer taskId;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<BatchNeed> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(BatchNeed batchNeed, AnalysisContext analysisContext) {
        cachedDataList.add(batchNeed);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            // 写入数据库
            SpringUtils.getBean(BatchNeedService.class).excelImportBatchNeed(cachedDataList, taskId);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        if (StringUtils.isNotEmpty(cachedDataList)) {
            SpringUtils.getBean(BatchNeedService.class).excelImportBatchNeed(cachedDataList, taskId);
        }
    }

    // 异常处理
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        ReadListener.super.onException(exception, context);
    }
}